<script lang="ts" setup>
import { ref, reactive, computed, defineAsyncComponent, watchEffect } from 'vue'
import {
  BizDataType,
  oldOverdueDataType,
  orderSummaryType,
  overdueDataType,
  productSnapshotType,
  queryOrderDetailInfoResponseData,
  objectListType
} from '@/api/order/types/order'
import { useRouter } from 'vue-router'
import { queryOrderDetailInfo, OrderConfirm } from '@/api/order'
import { getToken } from '@/utils/cache/cookies'
import { BizType, OrderStatusCodeType } from '@/types/enum'
import { ElMessage } from 'element-plus'
const BikeInfoPopover = defineAsyncComponent(() => import('@/components/popover/BikeInfo.vue'))
const RefundRecord = defineAsyncComponent(() => import('@/components/dialog/RefundRecord.vue'))
const RefundRecordRef = ref<InstanceType<typeof RefundRecord> | null>(null)
const dialogVisible = ref<boolean>(false)
const previousOrderId = ref<string | null>(null)
const previousUserId = ref<string | null>(null)
const orderId = ref<string>('')
const userId = ref<string>('')
const router = useRouter()
const open = async () => {
  if (orderId.value !== previousOrderId.value || userId.value !== previousUserId.value) {
    previousOrderId.value = orderId.value
    previousUserId.value = userId.value
    await getData()
  }
  dialogVisible.value = true
}
const setId = (newOrderId: string, newUserId: string) => {
  orderId.value = newOrderId
  userId.value = newUserId
}
defineExpose({ open, setId })
const emits = defineEmits(['refresh'])
const data = ref<queryOrderDetailInfoResponseData | null>(null)
const orderSummary = ref<orderSummaryType | null>(null)
const productSnapshot = ref<productSnapshotType | null>(null)
const bizData = ref<BizDataType | null>(null)
const overdueData = ref<overdueDataType | null>(null)
const oldOverdueData = ref<oldOverdueDataType | null>(null)
const objectList = ref<objectListType[]>([])
const loading = ref<boolean>(false)
const getData = async () => {
  try {
    loading.value = true
    const res = await queryOrderDetailInfo({
      token: getToken() ?? '',
      orderId: orderId.value,
      userId: userId.value
    })
    if (res.statusCode === '0') {
      data.value = res.data
      orderDetailStatus.value = data.value.bizData.orderDetailStatus
      orderSummary.value = data.value.orderSummary
      productSnapshot.value = data.value.productSnapshot
      bizData.value = data.value.bizData
      overdueData.value = data.value.overdueData
      oldOverdueData.value = data.value.oldOverdueData
      objectList.value = data.value.objectList
    }
    loading.value = false
  } catch (error) {
    console.error('Error fetching order details:', error)
    loading.value = false
  }
}
/** 订单状态 */
const orderDetailStatus = ref<OrderStatusCodeType>('0')
/**
 * @description 判断是否电池次卡
 */
const isBatteryTimesCard = computed(() => data.value?.bizType === BizType.BatteryTimesCard)
/**
 * @description 判断是否为长租车辆套餐
 */
const isBikeLongTerm = computed(() => data.value?.bizType === BizType.BikeLongTerm)
/**
 * @description 判断该订单是否已结束的状态
 */
const finishedStatuses = ['2', '3', '4', '6', '7', '8', '9', '10', '12']
const isOrderCompleted = computed(() => finishedStatuses.includes(orderDetailStatus.value))
/**
 * @description 判断是否含有赠送时长
 */
const hasGiftTime = computed(() => {
  const giftTime = orderSummary.value?.giftTime
  const isNotZeroTime = giftTime && giftTime !== '0天0小时0分' && giftTime !== '0次'
  const isNotOverdue = orderDetailStatus.value !== '5'

  return isNotZeroTime && isNotOverdue
})
/**
 * @description 判断订单状态是否为1或5 租用中 或逾期
 */
const isOrderActiveOrOverdue = computed(() => {
  return orderDetailStatus.value === '1' || orderDetailStatus.value === '5'
})
/**
 * @description 判断是否含押金套餐 即BatteryActivity和BikeLongTerm 也是含电套餐
 */
const isDepositTerm = computed(() => {
  return isBikeLongTerm.value || data.value?.bizType === BizType.BatteryActivity
})
/**
 * @description 判断订单为已取消
 */
const isOrderCancled = computed(() => {
  return orderDetailStatus.value === '12'
})
/**
 * @description 判断订单是否已操作延期
 */
const isOrderDelayed = computed(() => {
  return orderSummary.value?.delayDays !== '0'
})
/**
 * @description 判断订单是否是逾期状态
 */
const isOrderOverdue = computed(() => {
  return orderDetailStatus.value === '5'
})
/**
 * @description 判断订单是否是逾期状态并且逾期5小时内即逾期金额为0
 */
const isOrderSlightlyOverdue = computed(() => {
  return isOrderOverdue.value && overdueData.value?.overdueAmount === '0'
})
/**
 * @description 判断订单是否是逾期状态并且逾期大于5小时即逾期金额为大于0
 */
const isOrderSeriouslyOverdue = computed(() => {
  return isOrderOverdue.value && overdueData.value?.overdueAmount !== '0'
})
/**
 * @description 判断原始订单逾期费是否已支付
 */
const isOrderPaidOldoverdueAmount = computed(() => {
  return oldOverdueData.value?.paidAmount !== '0'
})
/**
 * @description 判断原始订单逾期费是否已支付
 */
const isOrderPaidOverdueAmount = computed(() => {
  return overdueData.value?.paidAmount !== '0'
})
/**
 * @description 判断订单是否可查看押金退款详情
 */
const isShowDepositRefundButton = computed(() => {
  return (
    orderDetailStatus.value == '3' ||
    orderDetailStatus.value == '4' ||
    orderDetailStatus.value == '8' ||
    orderDetailStatus.value == '9' ||
    orderDetailStatus.value == '10'
  )
})
/** 订单状态描述 */
const statusStyle = reactive({ color: '' })
const orderDetailStatusDescription = computed(() => {
  if (orderDetailStatus.value === '5') {
    /**
     * @todo orderDetailStatus为5则代表已逾期  不用将overdueFlag作为判断条件
     * @description overdueAmount 逾期费为0 则代表逾期5小时内
     */
    if (isOrderSlightlyOverdue.value) {
      return `已逾期${overdueData.value?.overdueTime}`
    } else {
      return `已逾期${overdueData.value?.overdueTime},已产生待支付逾期费用${overdueData.value?.overdueAmount}元`
    }
  } else {
    return bizData.value?.orderDetailStatusDescription
  }
})
// 订单状态颜色映射表
const orderStatusColors = {
  '-1': 'var(--xy-warning-light-color)',
  '0': 'var(--xy-warning-light-color)',
  '1': 'var(--xy-success-color)',
  '2': 'var(--xy-warning-light-color)',
  '3': 'var(--xy-warning-light-color)',
  '4': '#999999',
  '5': 'var(--xy-primary-color)',
  '6': 'var(--xy-warning-light-color)',
  '7': '#999999',
  '8': 'var(--xy-primary-color)',
  '9': 'var(--xy-warning-light-color)',
  '10': 'var(--xy-primary-color)',
  '12': '#999999',
  '98': '#3F9FF2',
  '99': '#39BCB7'
}
// 计算样式
const computedStatusStyle = computed(() => {
  if (isOrderSlightlyOverdue.value) {
    return { color: '#333333' }
  }
  return { color: orderStatusColors[orderDetailStatus.value] || '' }
})

// 动态更新样式
watchEffect(() => {
  Object.assign(statusStyle, computedStatusStyle.value)
})
/** -----------------------方法---------------------- */
/**
 * @description 查看退款记录
 */
const showRefundRecord = () => {
  if (!data.value?.orderId) return
  RefundRecordRef.value?.setId(data.value?.orderId)
  RefundRecordRef.value?.open()
}
const RefundInfoDialog = defineAsyncComponent(() => import('@/components/dialog/RefundInfo.vue'))
const RefundInfoDialogRef = ref<InstanceType<typeof RefundInfoDialog> | null>(null)
/**
 * @description 查看退款详情
 */
type ComponentType = 'rent' | 'deposit' | ''
const showRefundInfo = (type: ComponentType) => {
  dialogVisible.value = false
  RefundInfoDialogRef.value?.setId(orderId.value, type)
  RefundInfoDialogRef.value?.open()
}
/**
 * @description 取消订单
 */
const cancleOrder = async () => {
  try {
    const res = await OrderConfirm({
      token: getToken() ?? '',
      userId: userId.value,
      orderId: orderId.value
    })
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
      dialogVisible.value = false
      emits('refresh')
    }
  } catch (error) {
    console.error(error)
  }
}
/** 查看门店位置 */
const seeLocation = () => {
  dialogVisible.value = false
  router.push({
    name: 'StoreLocation',
    query: {
      longtitude: data.value?.storeInfo?.longtitude,
      latitude: data.value?.storeInfo?.latitude
    }
  })
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="订单信息"
    top="5vh"
    width="550px"
    class="order-info-dialog"
  >
    <div class="store-info" v-if="data?.storeInfo">
      <div class="store-info__image">
        <el-image
          v-for="(item, index) in data?.storeInfo?.imageUrls.split(',')"
          :key="index"
          :src="item"
          :preview-src-list="data?.storeInfo?.imageUrls.split(',')"
          :preview-teleported="true"
        />
      </div>
      <div class="store-info__title">
        <span class="red-click">{{ data?.storeInfo?.storeName }} ></span>
        <span>营业时间&nbsp;:&nbsp;{{ data?.storeInfo?.serviceTime }}</span>
      </div>
      <span class="store-info__contact"
        >门店信息:&nbsp;{{ data?.storeInfo?.contactPerson }}/{{
          data?.storeInfo?.contactPhone
        }}</span
      >
      <div class="store-info__location">
        <span>{{ data?.storeInfo?.address }}</span>
        <span class="red-click" @click="seeLocation">查看位置 ></span>
      </div>
    </div>
    <div class="order-info-dialog__state">
      <span
        >订单状态&nbsp;:&nbsp;<span :style="statusStyle">{{
          orderDetailStatusDescription
        }}</span></span
      >
    </div>
    <div
      class="order-info-dialog__refund-record"
      flex
      items-center
      justify-between
      v-if="data?.orderRefundData.refundCount !== 0"
    >
      <span
        >该订单有<span style="color: #f3860a">{{ data?.orderRefundData.refundCount }}</span
        >条退款记录</span
      >
      <span class="red-click" @click="showRefundRecord">查看详情 ></span>
    </div>
    <div class="order-info-dialog__remainderTime" flex justify-center>
      <span v-if="isOrderCompleted">结束时</span>
      <span
        >剩余<span>{{ isBatteryTimesCard ? '次数' : '时长' }}</span
        >&nbsp;:&nbsp;{{ orderSummary?.RemainingTime
        }}<span v-if="hasGiftTime" style="color: #333333"
          >(含{{ orderSummary?.giftTime }}赠送<span>{{ isBatteryTimesCard ? '次数' : '时长' }}</span
          >)</span
        ></span
      >
    </div>
    <div class="consump-info">
      <div class="consump-info__title">
        <div flex items-center justify-between>
          <div flex items-center>
            <span class="consump-info__title-name">{{ productSnapshot?.name }}</span>
            <div class="battery-power-container">
              <span>{{ productSnapshot?.inputVoltage }}</span>
            </div>
          </div>
          <span v-if="isBikeLongTerm"
            >车辆型号&nbsp;:&nbsp;<span style="color: #f3860a">{{ data?.productModel }}</span></span
          >
        </div>
        <div flex items-center justify-between>
          <div flex items-center>
            <span v-if="isBikeLongTerm"
              >车辆编号&nbsp;:&nbsp;<span>{{
                isOrderActiveOrOverdue ? bizData?.bikeCode : bizData?.originBikeCode
              }}</span></span
            >
            <span v-else-if="data?.bizType.includes('Battery')"
              >电池编号&nbsp;:&nbsp;<span>{{
                bizData?.batteryId == '1' ? '-' : bizData?.batteryId
              }}</span></span
            >
            <bike-info-popover
              v-if="(bizData?.bikeCode || bizData?.originBikeCode) && isBikeLongTerm"
              :origin-bike-code="bizData?.originBikeCode"
              :bike-code="bizData?.bikeCode"
              :order-detail-status="orderDetailStatus"
              @close="dialogVisible = false"
            />
          </div>
          <span v-if="isDepositTerm"
            >押金&nbsp;:&nbsp;<span class="deposit-money">{{ data?.productSnapshot.deposit }}</span
            >元</span
          >
        </div>
      </div>
      <div class="consump-info__image">
        <el-image
          v-for="(item, index) in data?.productSnapshot.imageUrls.split(',')"
          :key="index"
          :src="item"
          :preview-src-list="data?.productSnapshot.imageUrls.split(',')"
          :preview-teleported="true"
        />
      </div>
      <div class="consump-info__other" v-if="!isOrderCancled">
        <span>开始时间&nbsp;:&nbsp;{{ data?.bizData.startTime }}</span>
        <span v-if="!isBatteryTimesCard">已租赁时长&nbsp;:&nbsp;{{ data?.useTime }}</span>
        <span v-else>已租赁次数&nbsp;:&nbsp;{{ data?.bizData.rentUsedCount }}</span>
        <div v-if="isBikeLongTerm">
          <span>
            门店确认归还时间&nbsp;:&nbsp;{{ isOrderDelayed ? '-' : bizData?.bikeConfirm }}
          </span>
          <div class="delay-confirm-day" v-if="isOrderDelayed">
            订单已操作延期{{ orderSummary?.delayDays }}天确认。距离自动确认时间<span
              style="color: #f97d1e"
              >剩余{{ orderSummary?.delayDistanceTime }}</span
            >
          </div>
        </div>
        <span v-else>结束时间&nbsp;:&nbsp;{{ data?.finishedTime }}</span>
        <span v-if="JSON.stringify(data?.objectList) !== '[]' && isDepositTerm"
          >过期时间&nbsp;:&nbsp;{{ bizData?.endTime }}</span
        >
      </div>
    </div>
    <div class="consump-info2">
      <span
        >原始订单号&nbsp;:&nbsp;<span>{{ data?.orderId }}</span></span
      >
      <div>
        <span v-if="isBikeLongTerm">
          租赁周期 &nbsp;:&nbsp;{{ orderSummary?.originProductCount }}&nbsp;
          <span style="color: #999999"
            >({{ productSnapshot?.rentTimeDescription }}为一个租赁周期)</span
          >
        </span>
        <span v-else-if="isBatteryTimesCard">
          租赁次数 &nbsp;:&nbsp;
          {{ productSnapshot?.shortName }}
        </span>
        <span v-else>
          租赁天数 &nbsp;:&nbsp;
          {{ productSnapshot?.rentTimeDescription }}
        </span>
        <span style="margin-left: 54px"
          >租金&nbsp;:&nbsp;<span class="rent-money">{{ productSnapshot?.rent }}</span
          >元
          <span
            >(<span style="color: #f3860a">{{ bizData?.payStatus }}</span
            >)</span
          >
        </span>
      </div>
      <span>支付时间&nbsp;:&nbsp;{{ orderSummary?.createdTime }}</span>
      <span v-if="!isOrderCancled && JSON.stringify(data?.objectList) == '[]' && isDepositTerm"
        >过期时间&nbsp;:&nbsp;<span>{{ bizData?.endTime }}</span></span
      >
      <span v-else-if="isOrderCancled"
        >取消时间&nbsp;:&nbsp;<span>{{ bizData?.orderConfirm }}</span></span
      >
      <div class="consump-info2__overdue" v-if="isOrderSeriouslyOverdue">
        <span
          >订单逾期{{ oldOverdueData?.overdueTime }},
          <span v-if="!isOrderPaidOldoverdueAmount">用户待支付</span>
          <span v-else>用户已支付</span>
          <span v-if="!isOrderPaidOldoverdueAmount"
            >{{ oldOverdueData?.overdueAmount }}元的逾期费用</span
          >
          <span v-else>{{ oldOverdueData?.paidAmount }}元的逾期费用</span>
        </span>
        <span
          >支付时间&nbsp;:&nbsp;
          <span v-if="!isOrderPaidOldoverdueAmount" style="color: #f3860a">待支付</span>
          <span v-else>{{ oldOverdueData?.overduePayTime }}</span>
        </span>
      </div>
    </div>
    <div class="lease-renewal-info" flex flex-col v-if="JSON.stringify(data?.objectList) !== '[]'">
      <span class="lease-renewal-info__title">续租记录</span>
      <el-scrollbar max-height="260px">
        <div class="lease-renewal-info__container" flex flex-col>
          <div
            class="lease-renewal-info__item"
            v-for="(item, index) in objectList"
            :key="item.orderId"
          >
            <div class="current-use-order" v-if="item.currentUse == '1'">现使用</div>
            <span v-if="item.orderId"
              >订单号&nbsp;:&nbsp;<span>{{ item.orderId }}</span></span
            >
            <div v-if="isBikeLongTerm">
              <span
                >租赁周期&nbsp;:&nbsp;{{ item.productCount }}&nbsp;<span style="color: #999999"
                  >({{ productSnapshot?.rentTimeDescription }}为一个租赁周期)</span
                ></span
              >
              <span style="margin-left: 54px"
                >租金&nbsp;:&nbsp;<span class="rent-money">{{ item.rent }}</span
                >元</span
              >
            </div>
            <div v-else>
              <span>续租套餐&nbsp;:&nbsp;{{ productSnapshot?.name }}</span>
              <span style="margin-left: 54px"
                >租金&nbsp;:&nbsp;<span class="rent-money">{{ item.rent }}</span
                >元</span
              >
            </div>
            <span>支付时间&nbsp;:&nbsp;{{ item.createdTime }}</span>
            <div
              class="lease-renewal-info__overdue"
              v-if="isOrderSeriouslyOverdue && index == objectList.length - 1"
            >
              <span
                >订单逾期{{ overdueData?.overdueTime }},
                <span v-if="!isOrderPaidOverdueAmount">用户待支付</span>
                <span v-else>用户已支付</span>
                <span v-if="!isOrderPaidOverdueAmount"
                  >{{ overdueData?.overdueAmount }}元的逾期费用</span
                >
                <span v-else>{{ overdueData?.paidAmount }}元的逾期费用</span>
              </span>
              <span
                >支付时间&nbsp;:&nbsp;
                <span v-if="!isOrderPaidOverdueAmount" style="color: #f3860a">待支付</span>
                <span v-else>{{ overdueData?.overduePayTime }}</span>
              </span>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div>
      <el-button v-if="orderSummary?.cancelable == '1'" mt-20 w-full @click="cancleOrder" plain
        >取消订单</el-button
      >
      <el-button
        v-if="isOrderCancled && bizData?.payStatus == '已支付'"
        mt-20
        w-full
        @click="showRefundInfo('rent')"
        plain
        >查看退款详情</el-button
      >
      <el-button
        v-if="isShowDepositRefundButton"
        mt-20
        w-full
        @click="showRefundInfo('deposit')"
        plain
        >查看押金退款详情</el-button
      >
    </div>
  </el-dialog>
  <refund-record ref="RefundRecordRef" />
  <refund-info-dialog ref="RefundInfoDialogRef" />
</template>

<style scoped></style>
